package com.ebt.m.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.activity.FeedbackActivity;
import com.ebt.m.activity.MineInfoActivity;
import com.ebt.m.activity.SettingActivity;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.commons.utils.ToastUtil;
import com.ebt.m.commons.widgets.BaseRxFragment;
import com.ebt.m.data.bean.UserInfo;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.event.SyncCardEvent;
import com.ebt.m.update.UpdateService;
import com.ebt.m.users.CardActivity;
import com.ebt.m.users.bean.CardData;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.StateManager;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.utils.android.EBTUserInfoHelper;
import com.ebt.m.widget.EBTProgress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by andy on 2017/8/15.
 */

public class MineFragment extends BaseRxFragment implements View.OnClickListener, UpdateService.OnCheckVersionListener {

    @BindView(R.id.version_label)
    TextView versionLabel;
    @BindView(R.id.update_label)
    TextView updateLabel;
    @BindView(R.id.version_update_container)
    RelativeLayout mUpdateContainer;
    @BindView(R.id.feedback_container)
    RelativeLayout feedbackContainer;
    @BindView(R.id.user_avatar)
    ImageView userAvatar;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.user_phone)
    TextView userPhone;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.set_container)
    RelativeLayout setContainer;
    @BindView(R.id.action_user_detail)
    TextView actionUserDetail;
    @BindView(R.id.progress)
    EBTProgress progress;
    @BindView(R.id.card_container)
    RelativeLayout cardContainer;

    private ProgressDialog mProgressDialog;
    private UserInfo mUserLicenceInfo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_mine, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initViews();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden)
            initViews();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        initUser();
        initProgressDialog();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }

    public void initViews() {
        versionLabel.setText((ConfigData.VERSION_TEST ? "测试_" : "") + "V " + UpdateService.getApkVersionName());
        initUpdateVersion();
        configHeaderview();
    }

    private void configHeaderview() {
        EBTAPI opportunityApi = AppInitService.getEbtApi();
        opportunityApi.getCardData()
                .compose(RxUtil.rxTransformer(this))
                .subscribe(response -> {
                            if (response != null && response.getData() != null) {
                                CardData cardData = response.getData();
                                userName.setText(cardData.getUserName());
                                userPhone.setText(cardData.getPhone());
                                if (!TextUtils.isEmpty(cardData.getPortraitAddress()))
                                    Glide.with(getActivity())
                                            .load(cardData.getPortraitAddress())
                                            .error(R.drawable.empty_photo)
                                            .dontAnimate()
                                            .into(userAvatar);
                            }
                        }
                        , throwable -> {
                            throwable.printStackTrace();
                            NetUtils.checkHttpException(getContext(), throwable);
                        });
    }

    private void initUpdateVersion() {
        boolean hasNewApk = StateManager.getInstance(AppContext.getInstance()).getBoolean(StateManager.SETTING_ABOUT_NEW_HAS_APK);
        String apkUrl = StateManager.getInstance(AppContext.getInstance()).getString(StateManager.SETTING_ABOUT_NEW_APK_URL);
        if (hasNewApk && !TextUtils.isEmpty(apkUrl)) {
            updateLabel.setText("有新版本");
        } else {
            updateLabel.setText("已是最新");
        }
    }

    private void initUser() {
        //获取当前的用户的信息，如用户名，密码等
        mUserLicenceInfo = AppContext.getCurrentUser();
    }

    @OnClick({R.id.version_update_container, R.id.feedback_container, R.id.set_container, R.id.card_container, R.id.card_area})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.version_update_container: //版本更新
                TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_VERSION_CHECK);
                new UpdateService(getActivity()).updateVersion(this);
                break;
            case R.id.feedback_container: //意见反馈
                TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_FEEDBACK);
                Intent intent = new Intent(AppContext.getInstance(), FeedbackActivity.class);
                startActivity(intent);
                break;
            case R.id.set_container://设置
                Intent intent1 = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent1);
                break;
            case R.id.card_container://我的名片
               /* Intent webIntent = new Intent(getContext(), WebBaseActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(WebBaseActivity.WEB_TYPE_TITLE, "我的名片");
                bundle.putInt(WebBaseActivity.WEB_TYPE_FRAGMENT, WebBaseActivity.FRAGMENT_4COMPANY);
                bundle.putBoolean(WebBaseActivity.WEB_TYPE_HIDE_TOOLBAR, false);
                bundle.putString(WebBaseActivity.WEB_TYPE_LINK, ConfigData.AGENT_CARD_LINK);
                webIntent.putExtras(bundle);
                startActivity(webIntent);*/
                Intent cardIntent = new Intent(getContext(), CardActivity.class);
                startActivity(cardIntent);
                break;
            case R.id.card_area://我的头部区域
                Intent intent2 = new Intent(getActivity(), MineInfoActivity.class);
                startActivity(intent2);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAgentCardChangedEvent(SyncCardEvent cardEvent) {
        if (cardEvent.syncSuccessful) {
            EBTAPI ebtapi = AppInitService.getEbtApi();
            ebtapi.getERPCardInfo()
                   .compose(RxUtil.rxTransformer(this))
                    .subscribe(cardInfoBaseDataResult -> {
                        if (cardInfoBaseDataResult != null && cardInfoBaseDataResult.getData() != null) {
                            AppContext.getCurrentUser().setCardInfo(cardInfoBaseDataResult.getData());
                            EBTUserInfoHelper.saveUserKEY(AppContext.getCurrentUser());
                            configHeaderview();
                        }
                    }, throwable -> Logger.e(throwable.getMessage()));
        }
    }

    @Override
    public void onCheckStarted() {
        if (mProgressDialog != null)
            mProgressDialog.show();
    }

    private void initProgressDialog() {
        mProgressDialog = new ProgressDialog(getActivity(), R.style.LightDialog);
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setMessage("版本检测...");
    }

    @Override
    public void onCheckFinished(boolean hasNewVersion) {
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
        initUpdateVersion();
        if (!hasNewVersion)
            ToastUtil.show(getContext(), R.string.up_to_date);
    }

}
